import java.io.*;
import java.util.StringTokenizer;

public class 樱花 {
    public static PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
    public static Read in = new Read();
    public static int MAXN = 10001;
    public static int[] time = new int[MAXN * 10];
    public static int[] val = new int[MAXN * 10];
    public static int[] dp = new int[1001];
    public static int m;
    public static int n;
    public static void main(String[] args) throws IOException {
        String[] s1 = in.next().split(":");
        String[] s2 = in.next().split(":");
        int hour = Integer.parseInt(s2[0]) - Integer.parseInt(s1[0]);
        int mi = Integer.parseInt(s2[1]) - Integer.parseInt(s1[1]);
        m = hour * 60 + mi;
        int q = in.nextInt();
        while (q-- > 0) {
            int a = in.nextInt();
            int b = in.nextInt();
            int c = in.nextInt();
            if (c == 0) {
                int d = m;
                for (int i = 1; i <= d; i *= 2) {
                    time[++n] = i * a;
                    val[n] = i * b;
                    d -= i;
                }
                if (d > 0) {
                    time[++n] = d * a;
                    val[n] = d * b;
                }
            } else {
                for (int i = 1; i <= c; i *= 2) {
                    time[++n] = i * a;
                    val[n] = i * b;
                    c -= i;
                }
                if (c > 0) {
                    time[++n] = c * a;
                    val[n] = c * b;
                }
            }
        }
        out.println(compute());
        out.close();
    }

    private static int compute() {
        for (int i = 1; i <= n; i++) {
            for (int j = m; j >= time[i]; j--) {
                dp[j] = Math.max(dp[j], dp[j - time[i]] + val[i]);
            }
        }
        return dp[m];
    }


    public static class Read { // 自定义快速读入
        StringTokenizer st = new StringTokenizer("");
        BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));

        String next() throws IOException {
            while (!st.hasMoreTokens()) {
                st = new StringTokenizer(bf.readLine());
            }
            return st.nextToken();
        }

        String nextLine() throws IOException {
            return bf.readLine();
        }

        int nextInt() throws IOException {
            return Integer.parseInt(next());
        }

        long nextLong() throws IOException {
            return Long.parseLong(next());
        }

        double nextDouble() throws IOException {
            return Double.parseDouble(next());
        }
    }
}
